<template>
  <div class="detail-info">
    <div v-if="!isValidTask" class="empty-data">
      <el-empty description="暂无有效数据" />
    </div>
    <div v-else class="test-case-detail-container">
      <!-- 任务列表 -->
      <div class="section-title">任务列表</div>

      <!-- 任务表格 -->
      <el-table
        :data="formattedDemands"
        border
        stripe
        class="task-table"
        :header-cell-style="{ background: '#f5f7fa' }"
      >
        <el-table-column type="expand">
          <template #default="scope">
            <div class="test-cases-container">
              <div
                v-if="scope.row.testCases.length === 0"
                class="empty-test-cases"
              >
                <span class="empty-text">暂无测试用例</span>
              </div>
              <div v-else>
                <el-table
                  :data="scope.row.testCases"
                  border
                  size="small"
                  class="test-cases-table"
                >
                  <el-table-column prop="id" label="编号" width="80" />
                  <el-table-column
                    prop="description"
                    label="测试步骤"
                    min-width="180"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="preconditions"
                    label="预期结果"
                    min-width="180"
                    show-overflow-tooltip
                  />
                  <el-table-column label="状态" width="80">
                    <template #default>
                      <el-tag type="info" size="small" effect="plain">
                        待测试
                      </el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="taskName" label="任务名称" min-width="150" />
        <el-table-column prop="description" label="描述" min-width="180" />
        <el-table-column label="难度" width="80">
          <template #default="scope">
            <el-tag :type="getDifficultyType(scope.row.difficulty)">
              {{ scope.row.difficulty }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="timeRange" label="时间范围" width="180" />
        <el-table-column prop="expectedTime" label="预计时间" width="100" />
        <el-table-column label="测试用例数" width="100">
          <template #default="scope">
            <el-tag type="info" size="small">
              {{ scope.row.testCases.length }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="实际测试人员" width="180">
          <template #default="scope">
            <div
              v-if="
                scope.row.assignedTester && scope.row.assignedTester !== '-'
              "
              class="tester-info"
            >
              <!-- 测试人员姓名 -->
              <el-tag size="small" type="success">
                {{ scope.row.assignedTester }}
              </el-tag>

              <!-- 分析测试人员技术栈和等级 -->
              <div class="tester-tags">
                <!-- 查找对应的测试人员数据 -->
                <template v-if="getTestCaseTester(scope.row.assignedTester)">
                  <!-- 技术栈：红色 -->
                  <el-tag
                    v-for="(tech, index) in getTestCaseTester(
                      scope.row.assignedTester
                    ).technologyStack"
                    :key="'tech-' + index"
                    size="small"
                    type="danger"
                    style="margin: 2px"
                  >
                    {{ tech }}
                  </el-tag>

                  <!-- 能力等级：蓝色 -->
                  <el-tag
                    v-if="getTestCaseTester(scope.row.assignedTester).level"
                    size="small"
                    type="primary"
                    style="margin: 2px"
                  >
                    {{ getTestCaseTester(scope.row.assignedTester).level }}
                  </el-tag>
                </template>
              </div>
            </div>
            <span v-else>{{ scope.row.assignedTester || "-" }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { testCase as testCaseData } from "@/utils/cueWords";

const props = defineProps({
  task: {
    type: Object,
    required: true,
    default: () => ({}),
  },
});

// 确保taskData指向props.task
const taskData = computed(() => props.task || {});

// 验证任务数据是否有效
const isValidTask = computed(() => {
  return (
    taskData.value && typeof taskData.value === "object" && taskData.value.code
  );
});

// 提取需求列表
const demandsList = computed(() => {
  if (!isValidTask.value || !taskData.value.demandInfo) return {};

  const demands = {};
  for (const key in taskData.value.demandInfo) {
    if (key && key.startsWith("demand_")) {
      demands[key] = taskData.value.demandInfo[key];
    }
  }
  return demands;
});

// 格式化需求列表用于表格展示
const formattedDemands = computed(() => {
  const demands = [];

  for (const key in demandsList.value) {
    const demand = demandsList.value[key];

    // 关联该需求的测试用例
    const testCases =
      taskData.value.testCaseList?.filter(
        (tc) => tc.demandName === demand.demandName
      ) || [];

    demands.push({
      id: key,
      taskName: demand.demandName || "-",
      description: demand.demandDescription || "-",
      difficulty: demand.difficulty || "中",
      timeRange: `${formatDate(demand.startTime) || "未设置"} 至 ${
        formatDate(demand.endTime) || "未设置"
      }`,
      expectedTime: demand.expectedTime || "-",
      testCases: testCases,
      assignedTester:
        demand.assignedTester ||
        taskData.value.testCaseInfo?.assignedTester ||
        "-",
    });
  }

  return demands;
});

// 格式化日期为yyyy-MM-dd
const formatDate = (dateString) => {
  if (!dateString) return "未设置";

  try {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return dateString; // 如果无法解析为日期，返回原字符串

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");

    return `${year}-${month}-${day}`;
  } catch (error) {
    console.error("日期格式化错误:", error);
    return dateString;
  }
};

// 获取难度对应的标签类型
const getDifficultyType = (difficulty) => {
  switch (difficulty) {
    case "高":
      return "danger";
    case "中":
      return "warning";
    case "低":
      return "success";
    default:
      return "info";
  }
};

// 从testCase数据中获取测试人员信息
const getTestCaseTester = (testerName) => {
  try {
    // 解析testCase字符串为JSON对象
    const parsedTestCase = JSON.parse(testCaseData);
    if (parsedTestCase && parsedTestCase.developers) {
      // 查找匹配的测试人员
      const tester = parsedTestCase.developers.find(
        (dev) => dev.name === testerName
      );
      if (tester) {
        return {
          name: tester.name,
          expertise: tester.skills || [],
          technologyStack: tester.technologyStack || [],
          level: tester.level || "",
        };
      }
    }
  } catch (error) {
    console.error("解析测试人员数据失败:", error);
  }

  // 如果找不到或解析失败，返回基本信息
  return {
    name: testerName,
    expertise: [],
    technologyStack: [],
    level: "",
  };
};
</script>

<style scoped lang="scss">
.detail-info {
  padding: 0;
  background-color: #fff;

  .empty-data {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 200px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }

  .test-case-detail-container {
    padding: 16px;

    .section-title {
      font-size: 14px;
      font-weight: 600;
      color: #303133;
      margin: 20px 0 12px 0;
      padding-bottom: 8px;
      border-bottom: 1px solid #ebeef5;

      &:first-child {
        margin-top: 0;
      }
    }

    .basic-info-row {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 12px;

      .info-item {
        display: flex;
        align-items: center;
        margin-right: 24px;
        margin-bottom: 8px;

        .info-label {
          color: #606266;
          font-size: 14px;
          margin-right: 8px;
        }

        .info-value {
          font-weight: 500;
        }
      }
    }

    .dev-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-bottom: 16px;

      .empty-developer {
        .empty-text {
          color: #909399;
          font-size: 14px;
          font-style: italic;
        }
      }
    }

    .task-table {
      margin-bottom: 20px;
    }

    .test-cases-container {
      padding: 16px;
      background-color: #f8f8f8;

      .empty-test-cases {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100px;
        background-color: #fff;
        border-radius: 4px;

        .empty-text {
          color: #909399;
          font-size: 14px;
          font-style: italic;
        }
      }

      .test-cases-table {
        margin-bottom: 8px;
      }
    }
  }

  .description-content {
    max-height: 100px;
    overflow-y: auto;
    line-height: 1.5;
    white-space: pre-wrap;
  }

  :deep(.el-table__expanded-cell) {
    padding: 20px !important;
  }

  :deep(.el-table) {
    --el-table-header-bg-color: #f5f7fa;
    --el-table-row-hover-bg-color: #f0f7ff;

    th {
      font-weight: 600;
    }
  }
}
</style>
